package com.bsdk.install.device.socket.v1.cmd;

import lombok.extern.slf4j.Slf4j;

/**
 * @ProjectName: com.hlslock.utils.lock
 * @Package: com.hlslock.utils.lock
 * @ClassName: Cmd
 * @Author: HansYoung
 * @Description: cmd
 * @Createtime: 2023/12/11 08:44
 * @Modifytime: 2023/12/14 20:50
 * @Version: 1.0
 * @Copyright: ©2006-2023 版权所有. 深圳豪力士
 */
@Slf4j
public class Cmd implements ICmd {

    @Override
    public byte check_crc(byte[] ptr, int n)
    {
        int j = 8, i = 0;
        int cbit, out1;
        int crc = 0x79, crc_a = 0, crc_b = 0;
        do
        {
            crc_a = ptr[i++];

            j = 8;
            cbit = 1;
            do
            {
                crc_b = crc_a;
                crc_b = crc_b ^ crc;
                out1 = crc_b & cbit;
                //	crc_b=crc_b>>1;
                if (out1 != 0)
                {
                    crc = crc ^ 0X18;
                    crc = crc >> 1;
                    crc |= 0x80;
                }
                else
                    crc = crc >> 1;
                crc_a = crc_a >> 1;
                //	cbit=cbit<<1;
            } while (--j > 0);
        } while (--n > 0);
        return (byte)crc;
    }
    @Override
    public String pack_crc(byte[] data, int len) {
        int j = 0, i;
        byte[] buf = new byte[100];
        StringBuilder stringBuilder = new StringBuilder();

        buf[j++] = 0x02;
        buf[j++] = (byte) (len % 0x100);//len的低位
        buf[j++] = (byte) (len / 0x100);//len的高位
        for (i = 0; i < len; i++) {
            buf[j++] = data[i];
        }
        buf[j++] = check_crc(buf, j - 1);
        buf[j++] = (byte) 0xFF;
        for (i = 0; i < j; i++) {
            stringBuilder.append(String.format("%02X", buf[i]));
        }
        return stringBuilder.toString();
    }




}